package com.corpgovernment.organization.service.impl;

import cn.hutool.core.util.StrUtil;
import com.corpgovernment.api.basic.dto.CtripAccountInfo;
import com.corpgovernment.api.basic.request.UserIdentityRequest;
import com.corpgovernment.api.basic.vo.MbUserRegisterIdentityVO;
import com.corpgovernment.api.basic.vo.MbUserRegisterResponseVO;
import com.corpgovernment.api.organization.model.ffpinfo.UserFfpVo;
import com.corpgovernment.api.organization.model.idcard.UserIdCardVo;
import com.corpgovernment.api.organization.model.travelstandard.*;
import com.corpgovernment.api.organization.model.user.NameInfoBo;
import com.corpgovernment.api.organization.model.user.employee.UserBasicInfo;
import com.corpgovernment.api.organization.model.user.employee.UserIdentityVo;
import com.corpgovernment.api.organization.model.user.employee.UserIndexInfoVo;
import com.corpgovernment.api.travelstandard.soa.TravelStandardPostClient;
import com.corpgovernment.api.travelstandard.vo.CommonTravelStandradShow;
import com.corpgovernment.common.apollo.OrganizationApollo;
import com.corpgovernment.common.base.AbstractBaseService;
import com.corpgovernment.common.base.BaseUserInfo;
import com.corpgovernment.common.base.JSONResult;
import com.corpgovernment.common.utils.ListUtils;
import com.corpgovernment.organization.dataloader.BasicDataClientLoader;
import com.corpgovernment.organization.dataloader.UserRegisterClientDataloader;
import com.corpgovernment.organization.entity.db.MbOrgEmployeeInfo;
import com.corpgovernment.organization.entity.db.MbOrgUserFfpinfo;
import com.corpgovernment.organization.entity.db.MbOrgUserIdcard;
import com.corpgovernment.organization.entity.db.MbUserLogin;
import com.corpgovernment.organization.service.*;
import com.ctrip.corp.obt.generic.utils.CollectionUtils;
import com.ctrip.corp.obt.generic.utils.JsonUtils;
import com.ctrip.corp.obt.generic.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/*
用户首页信息查询服务
 */
@Service
@Slf4j
public class UserIndexInfoServiceImpl extends AbstractBaseService implements UserIndexInfoService {
    @Autowired
    private IOrganizationEmployeeService iOrganizationEmployeeService;
    @Autowired
    private IOrgUserIdCardService organizationUserIdCardService;
    @Autowired
    private IOrganizationUserFfpService organizationUserFfpService;
    @Autowired
    private TravelStandardPostClient travelStandardPostService;
    @Autowired
    private UserRegisterClientDataloader userRegisterClientDataloader;
    @Autowired
    private IUserLoginService userLoginService;
    @Autowired
    private BasicDataClientLoader basicDataClientLoader;
    @Autowired
    private OrganizationApollo organizationApollo;

    @Override
    public JSONResult<UserIndexInfoVo> getIndexIfo(BaseUserInfo baseUserInfo) {
        String uId = baseUserInfo.getUid();
        String orgId = baseUserInfo.getOrgId();

        //查询用户基础信息OrgEmployeeVo

        UserIndexInfoVo userIndexInfoVo = new UserIndexInfoVo();

        MbOrgEmployeeInfo mbOrgEmployeeInfo = iOrganizationEmployeeService.findByUid(uId);
        String eName = "";
        if (!StringUtils.isBlank(mbOrgEmployeeInfo.getFirstEnName())) {
            eName += mbOrgEmployeeInfo.getFirstEnName();
        }
        if (!StringUtils.isBlank(mbOrgEmployeeInfo.getMidEnName())) {
            eName += "/" + mbOrgEmployeeInfo.getMidEnName();
        }
        if (!StringUtils.isBlank(mbOrgEmployeeInfo.getLastEnName())) {
            eName += "/" + mbOrgEmployeeInfo.getLastEnName();
        }

        // 查询登录信息
        MbUserLogin loginUser = userLoginService.getByUid(uId);
        // 是否读取nameInfo的数据,T:读取  F:不读取
        boolean nameInfoReadSwitch = "T".equalsIgnoreCase(organizationApollo.getNameInfoReadSwitch());
        UserBasicInfo userBasicInfo = new UserBasicInfo();
        if(nameInfoReadSwitch && StrUtil.isNotBlank(mbOrgEmployeeInfo.getNameInfo())){
            NameInfoBo nameInfoBo = JsonUtils.parse(mbOrgEmployeeInfo.getNameInfo(), NameInfoBo.class);
            userBasicInfo.setSurname(nameInfoBo.getSurname());
            userBasicInfo.setGivenname(nameInfoBo.getGivenname());
            userBasicInfo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(nameInfoBo.getSurname(),nameInfoBo.getGivenname()));
            userBasicInfo.setFullName(nameInfoBo.getFullName());
            userBasicInfo.setNationality(nameInfoBo.getNationality());
        }else{
            userBasicInfo.setSurname(mbOrgEmployeeInfo.getLastEnName());
            userBasicInfo.setGivenname(mbOrgEmployeeInfo.getFirstEnName());
            userBasicInfo.setFullEnName(com.corpgovernment.organization.util.StrUtils.processFullEnName(mbOrgEmployeeInfo.getLastEnName(),mbOrgEmployeeInfo.getFirstEnName()));
            userBasicInfo.setFullName(mbOrgEmployeeInfo.getName());
            userBasicInfo.setNationality(mbOrgEmployeeInfo.getNationality());
        }
        userBasicInfo.setDeptName(baseUserInfo.getOrgName());
        userBasicInfo.setEmail(mbOrgEmployeeInfo.getEmail());
        userBasicInfo.setGender(mbOrgEmployeeInfo.getGender());
        userBasicInfo.setMobilePhone(mbOrgEmployeeInfo.getMobilePhone());
        userBasicInfo.setName(mbOrgEmployeeInfo.getName() + (StringUtils.isBlank(eName) ? "" : "(" + eName + ")"));
        userBasicInfo.setCnName(mbOrgEmployeeInfo.getName());
        userBasicInfo.setPortrait(mbOrgEmployeeInfo.getPortrait());
        userBasicInfo.setFirstName(mbOrgEmployeeInfo.getFirstEnName());
        userBasicInfo.setLastName(mbOrgEmployeeInfo.getLastEnName());
        userBasicInfo.setUid(uId);
        userBasicInfo.setPhoneNum(loginUser.getPhoneNum());
        userBasicInfo.setCountryCode(loginUser.getCountryCode());
        userBasicInfo.setAccountName(loginUser.getAccountName());
        userIndexInfoVo.setUserBasicInfo(userBasicInfo);

        //身份信息
        List<MbUserRegisterIdentityVO> identityVOList = getUserIdentityVo(baseUserInfo).stream().collect(Collectors.toList());
        userIndexInfoVo.setUserIdentityList(ListUtils.copyList(identityVOList,UserIdentityVo.class));
        //证件信息
        List<MbOrgUserIdcard> mbOrgUserIdcards = organizationUserIdCardService.findByEmployeeUid(uId);
        userIndexInfoVo.setUserIdcards(ListUtils.copyList(mbOrgUserIdcards, UserIdCardVo.class));

        //常旅客卡
        List<MbOrgUserFfpinfo> mbOrgUserFfpinfos = organizationUserFfpService.listByUid(uId);
        userIndexInfoVo.setUserFfpVos(ListUtils.copyList(mbOrgUserFfpinfos, UserFfpVo.class));

        //差标信息
        userIndexInfoVo.setStandardList(listTravelStandards(uId,orgId));

        CtripAccountInfo ctripAccountInfo = basicDataClientLoader.getCtripAccountInfo();
        if (Objects.nonNull(ctripAccountInfo)){
            userIndexInfoVo.setCtripAccountInfo(JsonUtils.convert(ctripAccountInfo, UserIndexInfoVo.CtripAccountInfo.class));
        }

        return JSONResult.success(userIndexInfoVo);
    }

    /**
     * 获取用户身份信息
     * @param baseUserInfo
     * @return
     */
    private List<MbUserRegisterIdentityVO> getUserIdentityVo(BaseUserInfo baseUserInfo) {
        List<MbUserRegisterIdentityVO> identityVOList = Lists.newArrayList();
        try {
            MbUserRegisterResponseVO userRegisterResponseVO = userRegisterClientDataloader.getAllIdentitySoa(new UserIdentityRequest(baseUserInfo.getUid(), baseUserInfo.getOrgId(), baseUserInfo.getCorpId()));
            if (userRegisterResponseVO == null || CollectionUtils.isEmpty(userRegisterResponseVO.getRoleList())) {
                return identityVOList;
            }
            identityVOList = new ArrayList<>(userRegisterResponseVO.getRoleList());
        } catch (Exception e) {
            log.error("获取用户身份信息失败", e);
        }
        return identityVOList;
    }

    /**
     * 差标列表
     */
    @Override
    public List<StandardInfo> listTravelStandards(String uid, String orgId) {
        List<StandardInfo> standardList = Lists.newArrayList();
        try {
            JSONResult<CommonTravelStandradShow> result = travelStandardPostService.travelStandardShowSoa(uid, orgId);
            if (result == null || !result.isSUCCESS()||result.getData()==null) {
                return null;
            }
            CommonTravelStandradShow travelStandard = result.getData();
            Map<String, List<Object>> map = Maps.newHashMap();
            map.put("flight", Lists.newArrayList(FlightTravelStandardVo.convertFrom(travelStandard.getFlight())));
            map.put("train", Lists.newArrayList(TrainTravelStandardVo.convertFrom(travelStandard.getTrain())));
            map.put("intlflight", Lists.newArrayList(IntlFlightTravelStandardVo.convertFrom(travelStandard.getIntlFlight())));
            map.put("hotel", HotelTravelStandardVo.convertFrom(travelStandard.getHotel()));
            map.put("intlhotel", IntlHotelTravelStandardVo.convertFrom(travelStandard.getIntlHotel()));
            map.put("car", Lists.newArrayList(CarTravelStandardVo.convertFrom(travelStandard.getCar())));
            map.put("airportTransfer", Lists.newArrayList(AirportTransferTravelStandardVo.convertFrom(travelStandard.getAirportTransfer())));
            map.put("trainTransfer", Lists.newArrayList(TrainTransferTravelStandardVo.convertFrom(travelStandard.getTrainTransfer())));

            map.forEach((k, v) -> {
                StandardInfo standardInfo = new StandardInfo();
                standardInfo.setSite(k);
                standardInfo.setContent(v);
                standardList.add(standardInfo);
            });
        } catch (Exception e) {
            log.error("获取差标失败",e);
        }
        return standardList;
    }
    @Override
    public JSONResult updateUserBasicInfo(UserBasicInfo userBasicInfo) {

        MbOrgEmployeeInfo mbOrgEmployeeInfo = new MbOrgEmployeeInfo();
        mbOrgEmployeeInfo.setGender(userBasicInfo.getGender());
        mbOrgEmployeeInfo.setNationality(userBasicInfo.getNationality());
        mbOrgEmployeeInfo.setMobilePhone(userBasicInfo.getMobilePhone());
        mbOrgEmployeeInfo.setEmail(userBasicInfo.getEmail());
        mbOrgEmployeeInfo.setUid(userBasicInfo.getUid());
        mbOrgEmployeeInfo.setPortrait(userBasicInfo.getPortrait());
        iOrganizationEmployeeService.update(mbOrgEmployeeInfo);

        return JSONResult.ok();
    }

    @Override
    public JSONResult<List<MbOrgUserIdcard>> findUserCardByEmployeeUid(String uId) {
        List<MbOrgUserIdcard> listMap = organizationUserIdCardService.findByEmployeeUid(uId);
        return JSONResult.success(listMap);
    }

    @Override
    public JSONResult<List<UserFfpVo>> findUserFfpByEmployeeUid(String uId) {
        List<MbOrgUserFfpinfo> mbOrgUserFfpinfos = organizationUserFfpService.listByUid(uId);
        return JSONResult.success(ListUtils.copyList(mbOrgUserFfpinfos, UserFfpVo.class));
    }
}